'use strict';

stareal
    .controller("RechargeWallletController", function ($scope, $api,$state,$alert,localStorageService,$stateParams) {
         $scope.selectStatus1=false;
        $scope.selectStatus10=false;
        $scope.selectStatus30=false;
        $scope.selectStatus50=false;
        $scope.headShow=false;
        $scope.dataLoadingStatus=false;
        $scope.payPrice=0;//支付钱
        localStorageService.set("RepayPrice",0);
        localStorageService.set("RepayPriceOrder",'');
        if($stateParams.app==1){
            $scope.headShow=true;
        }
        if($stateParams.accessToken==undefined||$stateParams.accessToken==null||$stateParams.accessToken==''){
            $scope.accessToken= localStorageService.get('token');
            var  rs = "main.rechargewallet-" + JSON.stringify({app:'',accessToken:''});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    localStorageService.set('token', '');
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
        }else{
            $scope.accessToken=$stateParams.accessToken;
        }
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger' || typeof WeixinJSBridge != "undefined") {
            $scope.Weishow = true;  //微信支付
            $scope.paySelect = 1;
        }else{
            $scope.paySelect = 4;
        }

        //获取用户信息  app/getShowcoin/payHomeCoin
        $api.get("app/getShowcoin/payHomeCoin", {accessToken:$scope.accessToken},false)
            .then(function (ret) {
                $scope.user = ret;
            });

        $scope.switchRecharge=function(price){

           $scope.payPrice=price;
           // $scope.payPrice=0.1;
            if (ua.match(/MicroMessenger/i) == 'micromessenger' || typeof WeixinJSBridge != "undefined") {
                $scope.paySelect = 1;
            }else{
                $scope.paySelect = 4;
            }
            $scope.payPriceshow=price.toFixed(2)+'元'
            if(price==2){
                $scope.selectStatus1=true;
                $scope.selectStatus10=false;
                $scope.selectStatus30=false;
                $scope.selectStatus50=false;
                $scope.RechargeWalllet_payDailogStatus=true;
            }else if(price==6){
                $scope.selectStatus1=false;
                $scope.selectStatus10=true;
                $scope.selectStatus30=false;
                $scope.selectStatus50=false;
                $scope.RechargeWalllet_payDailogStatus=true;
            }else if(price==12){
                $scope.selectStatus1=false;
                $scope.selectStatus10=false;
                $scope.selectStatus30=true;
                $scope.selectStatus50=false;
                $scope.RechargeWalllet_payDailogStatus=true;
            }else if(price==30){
                $scope.selectStatus1=false;
                $scope.selectStatus10=false;
                $scope.selectStatus30=false;
                $scope.selectStatus50=true;
                $scope.RechargeWalllet_payDailogStatus=true;
            }
        }
        $scope.hideRechargeWalllet_payDailog=function(){
             $scope.RechargeWalllet_payDailogStatus=false;
            $scope.selectStatus1=false;
            $scope.selectStatus10=false;
            $scope.selectStatus30=false;
            $scope.selectStatus50=false;
        }
        $scope.swithRechargeWalllet_pay=function(event,payNo){
            event.stopPropagation()//阻止冒泡
            $scope.paySelect=payNo;
            if(payNo==3){
                $scope.payPriceshow= ($scope.payPrice*50).toFixed(2)+'积分';
            }else {
                $scope.payPriceshow= $scope.payPrice.toFixed(2)+'元';
            }
        }

        $scope.goToRechargePaySuccess=function(event){
            event.stopPropagation()//阻止冒泡
            $scope.dataLoadingStatus=true;
            $scope.RechargeWalllet_payDailogStatus=false;
            var _params={buy_num: $scope.payPrice,pay_amount:$scope.payPrice,accessToken:$scope.accessToken}
            //支付宝
            if ( $scope.paySelect == 2) {
                //生成订单
                _params.pay_type=1;
               // var _params={buy_num: $scope.payPrice,pay_type:1,pay_amount:$scope.payPrice}
                $api.post("app/ShowcoinOrder/index/create", _params, false)
                    .then(function (ret) {
                        $scope.orderId = ret.data.order_id;
                        if($stateParams.app==1){
                            alert('order&'+$scope.orderId);
                            $scope.dataLoadingStatus=false;
                        }
                        $api.post("app/pay/showcoinPay/create", {//支付订单
                            orderId: $scope.orderId,
                            tradeType: 6,
                            payType: 4,
                            accessToken:$scope.accessToken
                        }, false)
                            .then(function (ret) {
                                localStorageService.set("RepayPrice",$scope.payPrice);
                                localStorageService.set("RepayPriceOrder",$scope.orderId);
                                $scope.dataLoadingStatus=false;
                                document.forms['alipaysubmit'].action = ret.data.action;
                                document.forms['alipaysubmit'].biz_content.value = ret.data.biz_content;
                                document.forms['alipaysubmit'].submit();
                            }, function (err) {
                                $alert.show(err);
                                $scope.dataLoadingStatus=false;
                                localStorageService.set("RepayPrice",0);
                                $state.go("main.rechargewallet",{})

                            })
                    }, function (err) {
                        $alert.show(err);
                        $scope.dataLoadingStatus=false;
                        localStorageService.set("RepayPrice",0);
                        $state.go("main.rechargewallet",{})
                    })
            }
            //微信支付
            if ( $scope.paySelect == 1) {
                //生成订单
                _params.pay_type=2;
                $api.post("app/ShowcoinOrder/index/create", _params, false)
                    .then(function (ret) {
                        $scope.orderId = ret.data.order_id;
                        if($stateParams.app==1){
                            alert('order&'+$scope.orderId);
                            $scope.dataLoadingStatus=false;
                        }
                        $api.post("app/pay/showcoinPay/create", {//支付订单
                            orderId: $scope.orderId,
                            tradeType: 6,
                            payType: 0,
                            openid: localStorageService.get('openid'),
                            accessToken:$scope.accessToken
                        }, false)
                            .then(function (ret) {
                                $scope.dataLoadingStatus=false;
                                function onBridgeReady() {
                                    WeixinJSBridge.invoke(
                                        'getBrandWCPayRequest',
                                        {
                                            "appId": ret.data.appId,                  //公众号名称，由商户传入wxd39f7e740343d507
                                            "timeStamp": ret.data.timeStamp,          //时间戳，自1970年以来的秒数
                                            "nonceStr": ret.data.nonceStr,            //随机串
                                            "package": ret.data.package,
                                            "signType": ret.data.signType,            //微信签名方式：
                                            "paySign": ret.data.paySign                  //微信签名
                                        }, function (res) {
                                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                                // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                                localStorageService.set("RepayPrice",$scope.payPrice);
                                                localStorageService.set("RepayPriceOrder",$scope.orderId);
                                               $state.go("my.rechargePaySuccess",{},true);
                                            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                                alert("您已取消支付");
                                               // $state.go("my.orders", {});
                                                localStorageService.set("RepayPrice",0);
                                                $state.go("main.rechargewallet",{})
                                            } else {
                                                alert("支付失败: [" + res.err_code + "] " + res.err_desc);
                                              //  $state.go("my.orders", {});
                                                localStorageService.set("RepayPrice",0);
                                                $state.go("main.rechargewallet",{})
                                            }
                                        }
                                    );
                                }
                                if (typeof WeixinJSBridge == "undefined") {
                                    if (document.addEventListener) {
                                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                    } else if (document.attachEvent) {
                                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                    }
                                } else {
                                    onBridgeReady();
                                }
                            }, function (err) {
                                $alert.show(err);
                                $scope.dataLoadingStatus=false;
                              //  $state.go("my.orders", {})
                                $state.go("main.rechargewallet",{})
                            })
                    }, function (err) {
                        $alert.show(err);
                        $scope.dataLoadingStatus=false;
                      //  $state.go("my.orders", {})
                        $state.go("main.rechargewallet",{})
                    })
            }
            // $state.go('my.rechargePaySuccess',{id:1},true);
            if( $scope.paySelect == 3){  //app/integral/payOrder
                //生成订单
                _params.pay_type=3;
                $api.post("app/ShowcoinOrder/index/create", _params,false)
                    .then(function (ret) {
                        $scope.orderId = ret.data.order_id;
                        if($stateParams.app==1){
                            alert('order&'+$scope.orderId);
                            $scope.dataLoadingStatus=false;
                        }
                        $api.post("app/integral/payOrder", {//支付订单app/integral/payOrder
                            orderId: $scope.orderId,
                            integral:$scope.user.integral,
                            accessToken:$scope.accessToken
                        }, false)
                            .then(function (ret) {
                             // console.log(ret);
                                $scope.dataLoadingStatus=false;
                                if($stateParams.app==1){
                                   // $scope.dataLoadingStatus=false;
                                    alert('success&'+$scope.payPrice);
                                }else{
                                    localStorageService.set("RepayPrice",$scope.payPrice);
                                    localStorageService.set("RepayPriceOrder",$scope.orderId);
                                    $state.go("my.rechargePaySuccess",{},true);
                                }
                            }, function (err) {
                                $scope.dataLoadingStatus=false;
                                $alert.show(err);
                                localStorageService.set("RepayPrice",0);
                                $state.go("main.rechargewallet",{})
                            })
                    }, function (err) {
                        $scope.dataLoadingStatus=false;
                        $alert.show(err);

                        localStorageService.set("RepayPrice",0);
                        $state.go("main.rechargewallet",{})
                    })
            }
            if( $scope.paySelect == 4){  //app/integral/payOrder  h5支付
                //生成订单
                _params.pay_type=2;
                $api.post("app/ShowcoinOrder/index/create", _params, false)
                    .then(function (ret) {
                        $scope.orderId = ret.data.order_id;
                        if($stateParams.app==1){
                            $scope.dataLoadingStatus=false;
                            alert('order&'+$scope.orderId);
                        }
                        $api.post("app/pay/showcoinPay/create", {//支付订单
                            orderId: $scope.orderId,
                            tradeType: 6,
                            payType: 22,
                            accessToken:$scope.accessToken
                        }, false)
                            .then(function (ret) {
                                $scope.dataLoadingStatus=false;
                                localStorageService.set("RepayPrice",$scope.payPrice);
                                localStorageService.set("RepayPriceOrder",$scope.orderId);
                                document.forms['WXpaysubmit'].action = ret.data.mweb_url;
                                document.forms['WXpaysubmit'].submit();
                                //$state.go("my.rechargePaySuccess",{id:$scope.orderId},true);
                            }, function (err) {
                                $scope.dataLoadingStatus=false;
                                localStorageService.set("RepayPrice",0);
                                $alert.show(err);
                                $state.go("main.rechargewallet",{})
                            })
                    }, function (err) {
                        $scope.dataLoadingStatus=false;
                        $alert.show(err);
                        localStorageService.set("RepayPrice",0);
                        $state.go("main.rechargewallet",{})
                    })
            }
        }
    });